'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
	async login() {
		const { ctx, app } = this
		// 获取用户名和密码
		const { user, pwd } = ctx.request.body
		// 查询用户信息
		const { user_info } = await ctx.service.user.findUser({ user, pwd });

		if (user_info) {
			// 获取当前用户角色权限信息
			const role = await ctx.service.user.findUserRole(user_info.role_id);
			// 生成令牌
			const token = app.jwt.sign({
				userInfo: {
					id: user_info.id,
					user: user_info.user,
					role_id: user_info.role_id,
					user_name: user_info.user_name,
					role_name: role.role_name
				},
			}, app.config.jwt.secret);
			// 返回结果
			ctx.body = {
				code: 200,
				msg: '登录成功',
				data: {
					userInfo: {
						id: user_info.id,
						user: user_info.user,
						role_id: user_info.role_id,
						user_name: user_info.user_name,
						role_name: role.role_name
					},
					token,
				}

			}
		} else {
			// 不存在 直接失败
			ctx.status = 401
			ctx.body = {
				code: 401,
				message: '账户密码错误， 请重新输入'
			}
		}
	}

	async getInfo() {
		const role = await this.ctx.service.user.findUserRole(this.ctx.state.userinfo.userInfo.role_id);
		this.ctx.body = {
			userInfo: this.ctx.state.userinfo.userInfo,
			routes: role.routes
		}
	}

	async getUsers() {
		const users = await this.ctx.service.user.getUsers()
		this.ctx.body = users
	}

	async getPsInfo() {
		const result = await this.ctx.service.user.getPsInfo();
		this.ctx.body = result
	}

	async modifyUserPermission() {
		const { ps_ids, role_id } = this.ctx.request.body;
		const result = this.ctx.service.user.modifyUserPermission({ ps_ids, role_id })
		if (result) {
			this.ctx.body = {
				code: 200,
				message: '权限更新成功'
			}
		} else {
			this.ctx.body = {
				code: 400,
				message: '权限更新失败'
			}
		}
	}
}

module.exports = UserController;
